<template>
  <div class="container">
    <div class="page-header">
      <div class="back-button">
        <el-button @click="$router.push('/main/biao')" icon="el-icon-back">返回</el-button>
      </div>
      <h1>新员工入职培训签到表</h1>
    </div>

    <div class="main-content">
      <div class="print-content">
        <el-form :model="formData" label-position="right" class="training-form" ref="trainingForm">
          <!-- 基本信息表格 -->
          <div class="info-section">
            <table class="info-table" border="1">
              <tbody>
                <tr>
                  <td class="label-cell">培训讲师：</td>
                  <td>
                    <el-input v-model="formData.trainer" :disabled="isViewMode" placeholder="请输入讲师姓名" />
                  </td>
                  <td class="label-cell">培训日期：</td>
                  <td>
                    <el-date-picker v-model="formData.trainingDate" type="date" placeholder="选择日期" format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd" :disabled="isViewMode" style="width: 100%" />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <!-- 培训内容表格 -->
          <div class="training-content-section">
            <table class="content-table" border="1">
              <thead>
                <tr>
                  <td rowspan="10" class="vertical-text">培训实施内容</td>
                  <td class="content-item">1、公司简介</td>
                  <td rowspan="10" class="vertical-text">培训考核说明</td>
                  <td rowspan="10" class="exam-desc">
                    1、培训考核方式：笔试。<br>
                    2、培训合格标准：考核成绩大于等于 60 分。<br>
                    3、凡考核成绩小于 60 分，延后报到日期，并于次日<br>重新参加培训并补考，如再次不合格则不予录用。
                  </td>
                </tr>
                <tr>
                  <td class="content-item">2、厂纪厂规</td>
                </tr>
                <tr>
                  <td class="content-item">3、安全常识（消防、生产、人身、危险品）</td>
                </tr>
                <tr>
                  <td class="content-item">4、考勤管理制度</td>
                </tr>
                <tr>
                  <td class="content-item">5、奖惩管理制度</td>
                </tr>
                <tr>
                  <td class="content-item">6、宿舍管理制度</td>
                </tr>
                <tr>
                  <td class="content-item">7、薪酬管理制度</td>
                </tr>
                <tr>
                  <td class="content-item">8、加班管理制度</td>
                </tr>
                <tr>
                  <td class="content-item">9、公司质量/环境/有害物质管理体系基础知识</td>
                </tr>
              </thead>
            </table>
          </div>

          <div class="form-actions">
            <el-button v-if="!isViewMode" type="info" @click="goToList" icon="el-icon-menu">列表</el-button>
            <el-button v-if="!isViewMode" type="primary" @click="saveData" icon="el-icon-check">保存</el-button>
          </div>
          <!-- 学员签名表格 -->
          <div class="student-section">
            <div class="section-header">
              <span class="title">学员签名</span>
              <div class="header-actions" v-if="!isViewMode">
                <el-button type="text" @click="addStudent" icon="el-icon-plus">添加学员</el-button>
                <el-button type="text" @click="deleteSelectedStudents" icon="el-icon-delete"
                  :disabled="!selectedStudents.length">
                  删除选中
                </el-button>
              </div>
            </div>

            <el-table ref="studentTable" :data="formData.students" border highlight-current-row
              :row-class-name="tableRowClassName" @selection-change="handleSelectionChange" class="student-table">
              <el-table-column v-if="!isViewMode" type="selection" width="50" align="center">
              </el-table-column>
              <el-table-column label="序号" type="index" width="60" align="center">
                <template slot-scope="scope">
                  <span class="index-cell">{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="姓名" prop="name" min-width="150">
                <template slot-scope="scope">
                  <el-form-item :prop="'students.' + scope.$index + '.name'" :rules="[
          { required: true, message: '请输入学员姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]" class="no-margin">
                    <el-input v-model="scope.row.name" :disabled="isViewMode" placeholder="请输入姓名" clearable
                      @blur="validateField('students.' + scope.$index + '.name')">
                      <i slot="prefix" class="el-icon-user"></i>
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="培训签到" width="100" align="center">
                <template slot-scope="scope">
                  <el-form-item :prop="'students.' + scope.$index + '.signIn'" class="no-margin">
                    <el-checkbox v-model="scope.row.signIn" :disabled="isViewMode"
                      @change="handleSignInChange(scope.row)">
                    </el-checkbox>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="考核成绩" width="120" align="center">
                <template slot-scope="scope">
                  <el-form-item :prop="'students.' + scope.$index + '.score'" :rules="[
          { required: true, message: '请输入考核成绩', trigger: 'blur' },
          { type: 'number', min: 0, max: 100, message: '分数范围为0-100', trigger: 'blur' }
        ]" class="no-margin">
                    <el-input-number v-model="scope.row.score" :disabled="isViewMode" :min="0" :max="100" :precision="1"
                      :step="1" size="small" controls-position="right" @change="handleScoreChange(scope.row)">
                    </el-input-number>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100" align="center">
                <template slot-scope="scope">
                  <el-tag :type="getScoreTagType(scope.row.score)" size="small">
                    {{ getScoreStatus(scope.row.score) }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>

            <div class="table-footer">
              <div class="statistics-info">
                <el-tag type="info" effect="plain">
                  <i class="el-icon-user"></i>
                  参训人数: {{ calculateAttendance() }} 人
                </el-tag>
                <el-tag type="success" effect="plain">
                  <i class="el-icon-circle-check"></i>
                  合格人数: {{ calculateQualified() }} 人
                </el-tag>
                <el-tag :type="getPassRateTagType()" effect="plain">
                  <i class="el-icon-data-analysis"></i>
                  合格率: {{ calculatePassRate() }}%
                </el-tag>
              </div>
            </div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { saveTrainingSign, getTrainingSignDetail } from '@/api/training'
import { Message } from 'element-ui'
import { formatDate } from '@/utils/date'

export default {
  data() {
    return {
      formData: {
        id: undefined,
        trainer: '',
        trainingDate: '',
        students: [
          {
            name: '',
            signIn: false,
            score: 0
          }
        ]
      },
      selectedStudents: [],
      selectAll: false,
      isViewMode: false
    };
  },
  created() {
    // 获取路由参数
    const { id, mode } = this.$route.query;

    // 设置页面模式
    this.isViewMode = mode === 'view';

    if (id) {
      // 编辑或查看模式，加载数据
      this.loadData(id);
    } else {
      // 新增模式，初始化空数据
      this.formData = {
        id: undefined,
        trainer: '',
        trainingDate: '',
        students: [{
          name: '',
          signIn: false,
          score: 0
        }]
      };
    }
  },
  watch: {
    'formData.students': {
      handler(newValue) {
        this.selectedStudents = newValue.map(item => item.signIn);
        this.updateSelectAll();
      },
      deep: true
    },
    selectedStudents: {
      handler(newValue) {
        this.updateSelectAll();
      },
      deep: true
    }
  },
  methods: {
    loadData(id) {
      getTrainingSignDetail(id).then(response => {
        const data = response.data;
        this.formData = {
          id: data.id,
          trainer: data.trainer,
          trainingDate: formatDate(data.trainingDate),
          students: data.students.map(student => ({
            name: student.studentName,
            signIn: student.signIn,
            score: student.score
          }))
        };
      }).catch(error => {
        Message.error('获取数据失败：' + error.message);
      });
    },
    addStudent() {
      if (this.isViewMode) return;
      this.formData.students.push({
        name: '',
        signIn: false,
        score: 0
      });
      this.selectedStudents.push(false);
    },
    toggleSelectAll() {
      this.selectedStudents = this.formData.students.map(() => this.selectAll);
    },
    deleteSelectedStudents() {
      if (this.isViewMode) return;
      const selectedIds = this.selectedStudents.map(item => item.name);
      this.formData.students = this.formData.students.filter(student => !selectedIds.includes(student.name));
      this.selectedStudents = [];
    },
    calculateAttendance() {
      return this.formData.students.filter(student => student.signIn).length;
    },
    calculateQualified() {
      return this.formData.students.filter(student => student.score >= 60).length;
    },
    calculatePassRate() {
      const attendance = this.calculateAttendance();
      if (attendance === 0) return 0;
      return ((this.calculateQualified() / attendance) * 100).toFixed(2);
    },
    updateSelectAll() {
      this.selectAll = this.selectedStudents.every(item => item);
    },
    goToList() {
      this.$router.push('/main/biao/pxqiandao-list');
    },
    saveData() {
      if (this.isViewMode) return;
      // 数据验证
      if (!this.formData.trainer) {
        this.$message.error('请输入培训讲师');
        return;
      }
      if (!this.formData.trainingDate) {
        this.$message.error('请选择培训日期');
        return;
      }
      if (!this.formData.students.length) {
        this.$message.error('请至少添加一名学员');
        return;
      }

      // 检查学员信息
      for (const student of this.formData.students) {
        if (!student.name) {
          this.$message.error('学员姓名不能为空');
          return;
        }
      }

      // 转换数据格式
      const saveData = {
        id: this.formData.id,
        trainer: this.formData.trainer,
        trainingDate: formatDate(this.formData.trainingDate),
        students: this.formData.students.map(student => ({
          studentName: student.name,
          signIn: student.signIn,
          score: student.score
        }))
      };

      // 调用保存接口
      saveTrainingSign(saveData).then(() => {
        this.$message({
          type: 'success',
          message: this.formData.id ? '更新成功！' : '保存成功！'
        });
        // 保存成功后跳转到列表页
        this.goToList();
      }).catch(error => {
        this.$message.error('保存失败：' + error.message);
      });
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.score >= 60) {
        return 'success-row';
      } else if (row.score > 0) {
        return 'warning-row';
      }
      return '';
    },
    handleSignInChange(row) {
      if (!row.signIn) {
        row.score = 0;
      }
    },
    handleScoreChange(row) {
      if (row.score > 0 && !row.signIn) {
        row.signIn = true;
      }
    },
    validateField(prop) {
      if (this.$refs.trainingForm) {
        this.$refs.trainingForm.validateField(prop);
      }
    },
    getScoreTagType(score) {
      if (score >= 60) return 'success';
      if (score > 0) return 'warning';
      return 'info';
    },
    getScoreStatus(score) {
      if (score >= 60) return '合格';
      if (score > 0) return '不合格';
      return '未考核';
    },
    getPassRateTagType() {
      const rate = this.calculatePassRate();
      if (rate >= 90) return 'success';
      if (rate >= 60) return 'warning';
      return 'danger';
    },
    handleSelectionChange(selection) {
      this.selectedStudents = selection;
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
  // background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  min-height: 100vh;
  position: relative;
}

.page-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
  padding: 20px;
  position: relative;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);

  h1 {
    font-size: 24px;
    color: #2c3e50;
    margin: 0;
    font-weight: 600;
    position: relative;
    padding-bottom: 10px;

    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 60px;
      height: 3px;
      background: linear-gradient(90deg, #409EFF, #67C23A);
      border-radius: 3px;
    }
  }
}

.back-button {
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
}

.main-content {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.form-actions {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.info-section {
  margin-bottom: 24px;

  .info-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #ebeef5;

    td {
      padding: 12px;
      border: 1px solid #ebeef5;
      vertical-align: middle;
    }

    .label-cell {
      background-color: #f8f9fa;
      font-weight: 500;
      color: #2c3e50;
      width: 120px;
      text-align: right;
    }
  }
}

.training-content-section {
  margin-bottom: 24px;

  .content-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #ebeef5;

    td {
      padding: 12px;
      border: 1px solid #ebeef5;
      vertical-align: middle;
    }

    .vertical-text {
      writing-mode: vertical-lr;
      text-orientation: upright;
      background-color: #f0f7ff;
      color: #1890ff;
      font-weight: bold;
      width: 40px;
      text-align: center;
      padding: 10px;
    }

    .content-item {
      text-align: left;
      padding: 12px 16px;
      color: #2c3e50;
    }

    .exam-desc {
      padding: 16px;
      line-height: 1.8;
      color: #2c3e50;
      background-color: #f8f9fa;
    }
  }
}

.student-section {
  margin-bottom: 24px;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #f0f7ff;
    padding: 16px 20px;
    border-radius: 8px 8px 0 0;
    margin-bottom: 0;

    .title {
      color: #1890ff;
      font-weight: bold;
      font-size: 16px;
    }

    .header-actions {
      display: flex;
      gap: 16px;

      .el-button {
        padding: 0;
        font-size: 14px;

        &:hover {
          color: #409EFF;
        }

        &[disabled] {
          color: #C0C4CC;
        }
      }
    }
  }

  .student-table {
    border-radius: 0 0 8px 8px;
    overflow: hidden;

    ::v-deep {
      .el-table__header-wrapper {
        th {
          background-color: #f8f9fa;
          color: #2c3e50;
          font-weight: 600;
        }
      }

      .el-table__row {
        &:hover {
          background-color: #f5f7fa;
        }

        &.warning-row {
          background-color: #fdf6ec;
        }

        &.success-row {
          background-color: #f0f9eb;
        }
      }

      .el-input__inner {
        border-radius: 4px;
      }

      .el-checkbox__inner {
        border-radius: 2px;
      }

      .el-input-number {
        width: 100%;
      }
    }

    .index-cell {
      display: inline-block;
      width: 24px;
      height: 24px;
      line-height: 24px;
      background-color: #f0f7ff;
      color: #1890ff;
      border-radius: 12px;
      font-size: 14px;
    }
  }

  .no-margin {
    margin-bottom: 0;
  }

  .table-footer {
    margin-top: 20px;
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 8px;

    .statistics-info {
      display: flex;
      justify-content: space-evenly;
      gap: 24px;

      .el-tag {
        padding: 8px 16px;
        font-size: 14px;
        display: flex;
        align-items: center;

        i {
          margin-right: 6px;
        }
      }
    }
  }
}

.statistics-section {
  margin-top: 24px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;

  .statistics-info {
    display: flex;
    justify-content: space-around;
    color: #2c3e50;
    font-weight: 500;

    span {
      padding: 8px 16px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }
  }
}

@media screen and (max-width: 768px) {
  .container {
    padding: 16px;
  }

  .page-header {
    padding: 16px;
    margin-bottom: 20px;

    h1 {
      font-size: 20px;
    }
  }

  .main-content {
    padding: 16px;
  }

  .form-actions {
    flex-direction: column;

    .el-button {
      width: 100%;
    }
  }

  .statistics-section {
    .statistics-info {
      flex-direction: column;
      gap: 8px;

      span {
        text-align: center;
      }
    }
  }
}

@media print {
  .container {
    margin: 0;
    padding: 0;
    background: none;
    min-height: auto;
  }

  .page-header,
  .form-actions,
  .back-button {
    display: none !important;
  }

  .main-content {
    padding: 0;
    background: none;
    box-shadow: none;
  }

  .info-section,
  .training-content-section,
  .student-section {
    margin-bottom: 20px;
    page-break-inside: avoid;
  }

  table {
    border: 1px solid #000;

    td,
    th {
      border: 1px solid #000;
      padding: 8px;
      font-size: 14px;
    }
  }

  .statistics-section {
    border-top: 1px solid #000;
    margin-top: 20px;
    padding-top: 16px;
  }

  @page {
    margin: 2cm;
    size: A4 portrait;
  }
}
</style>